#include "SpriteCounter.h"
#include "..\base\Engine.h"
#include "..\utils\Log.h"

namespace ds {

SpriteCounter::SpriteCounter(SpriteNode* batchNode,const Rect& startOffset,int width,int digits) 
	: m_StartOffset(startOffset) , m_Width(width) , m_Digits(digits) , m_Sprites(batchNode), m_Start(1) {
		
	prepare(Vec2(0,0),startOffset,digits,Color(1.0f,1.0f,1.0f,1.0f));	
}

SpriteCounter::SpriteCounter(SpriteNode* batchNode,const Vec2& pos,const Rect& startOffset,int digits,const Color& color) 
	: m_StartOffset(startOffset) , m_Digits(digits) , m_Sprites(batchNode), m_Start(1) {
	prepare(pos,startOffset,digits,color);
}

void SpriteCounter::prepare(const Vec2& pos,const Rect& startOffset,int digits,const Color& color) {
	m_Scale = ds::Vec2(1.0,1.0f);
	m_Position = pos;
	for ( int i = 0; i < digits; ++i ) {
		Number n;
		n.handle = m_Sprites->add(ds::Vec2(0,0),m_StartOffset);
		n.counter = -1;
		m_Numbers.push_back(n);
		if ( i != 0 ) {
			m_Start *= 10;
		}
	}
	m_Width = startOffset.width();
	m_Color = color;
	m_Value = -1;
	m_Height = startOffset.height();
	setCounter(0);
	setPos(pos);
	setColor(color);
}

SpriteCounter::~SpriteCounter() {
}

void SpriteCounter::setColor(const ds::Color& color) {
	m_Color = color;
	for ( size_t i = 0; i < m_Numbers.size(); ++i ) {
		m_Sprites->setColor(m_Numbers[i].handle,color);
	}
}

void SpriteCounter::setActive(bool active) {
	for ( size_t i = 0; i < m_Numbers.size(); ++i ) {
		m_Sprites->setVisible(m_Numbers[i].handle,active);
	}
}

void SpriteCounter::setScale(const Vec2& scale) {
	m_Scale = scale;
	Vec2 tmp = m_Position;
	if ( scale.y != 1.0f ) {
		tmp.y += m_Height * (1.0f - m_Scale.y) * 0.5f;
	}
	for ( size_t i = 0; i < m_Numbers.size(); ++i ) {
		m_Sprites->setScale(m_Numbers[i].handle,scale);
		m_Sprites->setPosition(m_Numbers[i].handle,tmp);
		tmp.x += m_Width * m_Scale.x;
	}
}

void SpriteCounter::setCounter(int value) {
	if ( value >= 0 ) {
		int tmp = value;
		if ( tmp != m_Value ) {
			m_Value = tmp;
			int x = m_Start;
			int r = 0;		
			for ( int i = 0; i < m_Digits; ++i ) {
				r = tmp / x;
				m_Sprites->setOffset(m_Numbers[i].handle,getOffset(r));
				tmp = tmp - r*x;
				x /= 10;
			}
		}		
	}
}

Rect SpriteCounter::getOffset(int nr) {
	int yp = nr*m_Width;	
	Rect ret = m_StartOffset;
	ret.left += yp;
	ret.right = ret.left + m_Width;
	return ret;
}

void SpriteCounter::setPos(const Vec2& pos) {
	m_Position = pos;
	Vec2 tmp = pos;
	for ( size_t i = 0; i < m_Numbers.size(); ++i ) {
		m_Sprites->setPosition(m_Numbers[i].handle,tmp);
		tmp.x += m_Width * m_Scale.x;
	}
}

}
